package org.yys.demo;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.yys.constant.MqConstant;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class KeyDemo {


    public void keyProducer() throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建生产者
        DefaultMQProducer producer = new DefaultMQProducer("key-producer-group");
        producer.setNamesrvAddr(MqConstant.NAMESRV_ADDR);
        producer.start();

        for (int i = 0; i < 10; i++) {

            String uuid = UUID.randomUUID().toString();
            System.out.printf("uuid:%s%n",uuid);
            // 创建消息
            Message message = new Message("key-topic", "tag",uuid, ("这是一个简单的消息. key:"+uuid).getBytes());

            // 发送消息
            SendResult send = producer.send(message);
            System.out.println("result:"+send);
        }


        producer.shutdown();

    }

    public void keyConsumer() throws MQClientException, InterruptedException, IOException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("key-consumer-group");
        consumer.setNamesrvAddr(MqConstant.NAMESRV_ADDR);
        consumer.subscribe("key-topic","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt messageExt = list.get(0);
                System.out.printf("消费者接收消息...%s;%n",messageExt.getKeys());
                System.out.printf("message:%s%n",new String(messageExt.getBody()));
//                System.out.println("context:"+consumeConcurrentlyContext);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();


        // 线程睡100s. 注:由于监听器在另一个线程中, 不会被当前线程的sleep影响.
        System.in.read();

    }



}
